package monitor

import (
	"fmt"
	"time"

	"apiGateWay/internal/config"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	// HTTPRequestsTotal 总请求数
	HTTPRequestsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "http_requests_total",
			Help: "HTTP 请求总数",
		},
		[]string{"method", "path", "status"},
	)

	// HTTPRequestDuration 请求耗时
	HTTPRequestDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "http_request_duration_seconds",
			Help:    "HTTP 请求耗时（秒）",
			Buckets: prometheus.DefBuckets,
		},
		[]string{"method", "path"},
	)

	// HTTPRequestSize 请求大小
	HTTPRequestSize = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "http_request_size_bytes",
			Help:    "HTTP 请求大小（字节）",
			Buckets: []float64{100, 500, 1000, 5000, 10000, 50000, 100000},
		},
		[]string{"method", "path"},
	)

	// HTTPResponseSize 响应大小
	HTTPResponseSize = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "http_response_size_bytes",
			Help:    "HTTP 响应大小（字节）",
			Buckets: []float64{100, 500, 1000, 5000, 10000, 50000, 100000},
		},
		[]string{"method", "path"},
	)

	// ActiveConnections 活跃连接数
	ActiveConnections = prometheus.NewGauge(
		prometheus.GaugeOpts{
			Name: "http_active_connections",
			Help: "当前活跃连接数",
		},
	)
)

// InitPrometheus 初始化 Prometheus 监控
func InitPrometheus(cfg *config.Config) {
	prometheus.MustRegister(HTTPRequestsTotal)
	prometheus.MustRegister(HTTPRequestDuration)
	prometheus.MustRegister(HTTPRequestSize)
	prometheus.MustRegister(HTTPResponseSize)
	prometheus.MustRegister(ActiveConnections)
}

// PrometheusHandler Prometheus 处理器
func PrometheusHandler() gin.HandlerFunc {
	handler := promhttp.Handler()
	return func(c *gin.Context) {
		handler.ServeHTTP(c.Writer, c.Request)
	}
}

// PrometheusMiddleware Prometheus 监控中间件
func PrometheusMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 增加活跃连接数
		ActiveConnections.Inc()
		defer ActiveConnections.Dec()

		// 记录请求开始时间
		start := time.Now()

		// 记录请求大小
		if c.Request.ContentLength > 0 {
			HTTPRequestSize.WithLabelValues(c.Request.Method, c.FullPath()).Observe(float64(c.Request.ContentLength))
		}

		// 处理请求
		c.Next()

		// 记录响应大小
		if c.Writer.Size() > 0 {
			HTTPResponseSize.WithLabelValues(c.Request.Method, c.FullPath()).Observe(float64(c.Writer.Size()))
		}

		// 记录请求耗时
		duration := time.Since(start).Seconds()
		HTTPRequestDuration.WithLabelValues(c.Request.Method, c.FullPath()).Observe(duration)

		// 记录请求总数
		HTTPRequestsTotal.WithLabelValues(c.Request.Method, c.FullPath(), fmt.Sprintf("%d", c.Writer.Status())).Inc()
	}
}

